package com.example.bookstore.fliter;

import com.alibaba.fastjson.JSON;
import com.example.bookstore.common.BaseContext;
import com.example.bookstore.common.Result;
import com.example.bookstore.entity.Admin;
import com.example.bookstore.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    private static  final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response =(HttpServletResponse) servletResponse;

        String requestURI=request.getRequestURI();


        String[] urls=new String[]{"/admin/login","/admin/logout","/common/**","/user/login","/user/logout",
                "/login_page/**","/js/**","/plugins/**","/element-ui/**","/css/**","/image/**","/styles/**",
                "/img/**","/book/page","/user","/index.html"
                };

        boolean check = check(urls, requestURI);
        if (check){
            filterChain.doFilter(request,response);
            return;
        }
        if (request.getSession().getAttribute("user")!=null){
            User user = (User)request.getSession().getAttribute("user");
            Integer userId = user.getId();
            BaseContext baseContext=new BaseContext();
            baseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }
        if (request.getSession().getAttribute("admin")!=null){
            Admin admin= (Admin) request.getSession().getAttribute("admin");
            BaseContext baseContext=new BaseContext();
            Integer empId = admin.getId();
            baseContext.setCurrentId(empId);
            filterChain.doFilter(request,response);
            return;
        }

        System.out.println("无登录");
        request.getRequestDispatcher("/login_page/login.html").forward(request,response);


    }
    public boolean check(String[] urls,String requestURI){
        for (String url:urls){
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
